//
//  NoWeChatInstallLogView.m
//  MeterMart
//
//  Created by ENERGY on 2018/11/12.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "NoWeChatInstallLogView.h"

static int countTime = 599;
@interface NoWeChatInstallLogView()<UITextFieldDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UITextField * phoneNumTextField;//电话号
@property (nonatomic, strong)UITextField * verificationCodeTextField;//验证码
@property (nonatomic, strong)UIButton * verificationCodeBtn;//验证码按钮
@property (nonatomic, strong)UITextField * inviteTextField;//邀请码
@property (nonatomic, strong)UIButton * boundBtn;//绑定按钮
@property (nonatomic, strong)NSTimer * timer;
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * verificationString;
@property (nonatomic, strong) UIActivityIndicatorView * activityIndicator;//菊花

- (void)test:(NSTimer *)timmer;
- (void)showError:(NSError*)error;
@end

@implementation NoWeChatInstallLogView(networking)
- (void)sendnum{
    NSDictionary * dic = @{
                           @"phone":self.phoneNumTextField.text
                           };
    [self.activityIndicator startAnimating];
    [[AFAppDotNetAPIClient sharedClient] POST:@"wxno/sendnum" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.activityIndicator stopAnimating];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.verificationCodeBtn.enabled = NO;
            //初始化定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test:) userInfo:nil repeats:YES];
        }else{
            [self makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self.activityIndicator stopAnimating];
    }];
}
- (void)bindPhoneNum{
    NSDictionary * dic = @{
                           @"phone":self.phoneNumTextField.text,
                           @"code":self.verificationCodeTextField.text
                           };
    [self.activityIndicator startAnimating];
    [[AFAppDotNetAPIClient sharedClient] POST:@"wxno/bindphone" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.activityIndicator stopAnimating];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [UserModel sharedInstanced].userID = responseObject[@"list"][@"unionid"];
            if (self.bindPhoneSuccess) {
                self.bindPhoneSuccess();
            }
        }else{
            [self makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self.activityIndicator stopAnimating];
    }];
}
@end
@implementation NoWeChatInstallLogView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.alpha = 0;
        [self addSubview:self.tableView];
    }return self;
}

#pragma mark - init
- (UIActivityIndicatorView *)activityIndicator{
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
        //        [self.view addSubview:self.activityIndicator];
        //设置小菊花的frame
        _activityIndicator.frame= CGRectMake(0, 0, 100/WIDTH_6_SCALE, 100/WIDTH_6_SCALE);
        _activityIndicator.center = self.center;
        //设置小菊花颜色
        _activityIndicator.color = getColor(textGrayColor);
        //设置背景颜色
        _activityIndicator.backgroundColor = [UIColor colorWithRed:231 green:231 blue:231 alpha:1];
        //刚进入这个界面会显示控件，并且停止旋转也会显示，只是没有在转动而已，没有设置或者设置为YES的时候，刚进入页面不会显示
        _activityIndicator.hidesWhenStopped = YES;
    }return _activityIndicator;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.frame.size.height) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.frame.size.height)];
        //标题
        UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        titleLab.text = @"登录";
        titleLab.textColor = [UIColor blackColor];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.font = DEF_FontSize_14;
        titleLab.backgroundColor = [UIColor clearColor];
        [_headerView addSubview:titleLab];
        //手机号
        self.phoneNumTextField = [[UITextField alloc] initWithFrame:CGRectMake(40/WIDTH_6_SCALE, 43/WIDTH_6_SCALE + titleLab.bottom, SCREEN_WIDTH - 80/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        self.phoneNumTextField.delegate = self;
        self.phoneNumTextField.placeholder = @"请输入手机号";
        self.phoneNumTextField.font = DEF_FontSize_14;
        self.phoneNumTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * phoneNumPlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.phoneNumTextField.height)];
        phoneNumPlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *phoneNumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 11/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        phoneNumImageView.image = [UIImage imageNamed:@"boundPhone"];
        [phoneNumPlaceHoldImgBG addSubview:phoneNumImageView];
        self.phoneNumTextField.leftView = phoneNumPlaceHoldImgBG;
        self.phoneNumTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.phoneNumTextField];
        //验证码
        self.verificationCodeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.phoneNumTextField.bottom + 16/WIDTH_6_SCALE, 191/WIDTH_6_SCALE, self.phoneNumTextField.height)];
        self.verificationCodeTextField.delegate = self;
        self.verificationCodeTextField.placeholder = @"输入验证码";
        self.verificationCodeTextField.font = DEF_FontSize_14;
        self.verificationCodeTextField.backgroundColor = getColor(mainColor);
        self.verificationCodeTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * verificationCodePlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.verificationCodeTextField.height)];
        verificationCodePlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *verificationCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        verificationCodeImageView.image = [UIImage imageNamed:@"lock"];
        [verificationCodePlaceHoldImgBG addSubview:verificationCodeImageView];
        self.verificationCodeTextField.leftView = verificationCodePlaceHoldImgBG;
        self.verificationCodeTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.verificationCodeTextField];
        //验证码按钮
        self.verificationCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.verificationCodeTextField.right + 10/WIDTH_6_SCALE, self.verificationCodeTextField.top, SCREEN_WIDTH - self.verificationCodeTextField.left * 2 - 10/WIDTH_6_SCALE - self.verificationCodeTextField.width, self.verificationCodeTextField.height)];
        [self.verificationCodeBtn setBackgroundColor:getColor(mainRedColor)];
        self.verificationCodeBtn.titleLabel.font = DEF_FontSize_14;
        [self.verificationCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.verificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.verificationCodeBtn addTarget:self action:@selector(verificationCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:self.verificationCodeBtn];
        //邀请码
        self.inviteTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.verificationCodeTextField.bottom + 16/WIDTH_6_SCALE, self.phoneNumTextField.width, self.phoneNumTextField.height)];
        self.inviteTextField.placeholder = @"输入邀请码";
        self.inviteTextField.backgroundColor = getColor(mainColor);
        self.inviteTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * invitePlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.verificationCodeTextField.height)];
        invitePlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *inviteImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        inviteImageView.image = [UIImage imageNamed:@"lock"];
        [invitePlaceHoldImgBG addSubview:inviteImageView];
        self.inviteTextField.leftView = invitePlaceHoldImgBG;
        self.inviteTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.inviteTextField];
        self.inviteTextField.hidden = YES;
        //绑定按钮
        self.boundBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.inviteTextField.bottom + 38/WIDTH_6_SCALE, self.phoneNumTextField.width, 40/WIDTH_6_SCALE)];
        [self.boundBtn setBackgroundColor:getColor(mainColor)];
        [self.boundBtn setTitle:@"绑定" forState:UIControlStateNormal];
        self.boundBtn.titleLabel.font = DEF_FontSize_14;
        [self.boundBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        [self.boundBtn addTarget:self action:@selector(boundBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:self.boundBtn];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.boundBtn.bottom + 20/WIDTH_6_SCALE);
    }return _headerView;
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
//    if (self.backBtnClickBlock) {
//        self.backBtnClickBlock();
//    }
}
- (void)verificationCodeBtnClick:(UIButton *)sender{
    if (self.phoneNumTextField.text.length == 0 || [self.phoneNumTextField.text isEqualToString:@""] || self.phoneNumTextField.text == nil) {
        [self makeToast:@"请输入手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    if ([self valiMobile:self.phoneNumTextField.text]) {
        [self endEditing:YES];
        [self sendnum];//发送验证码
    }else{
        [self makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
    }
}
- (void)boundBtnClick:(UIButton *)sender{
    NSLog(@"绑定");
    if (self.phoneNumTextField.text.length == 0 || [self.phoneNumTextField.text isEqualToString:@""] || self.phoneNumTextField.text == nil) {
        [self makeToast:@"请输入手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    if ([self valiMobile:self.phoneNumTextField.text]) {
        if (self.verificationCodeTextField.text.length == 0 || [self.verificationCodeTextField.text isEqualToString:@""] || self.verificationCodeTextField.text == nil) {
            [self makeToast:@"请输入验证码" duration:1 position:CSToastPositionCenter];
        }else{
            [self bindPhoneNum];
        }
    }else{
        [self makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
    }
}
- (void)test:(NSTimer *)timer{
    if (countTime != 1) {
        countTime -= 1;
        self.verificationCodeBtn.enabled = NO;
        [self.verificationCodeBtn setTitle:[NSString stringWithFormat:@"剩余%i秒", countTime] forState:UIControlStateNormal];
    } else {
        self.verificationCodeBtn.enabled = YES;
        [self.verificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        countTime = 30;
        //停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}
#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneNumTextField) {
        self.phoneString = string;
    }
    if (textField == self.verificationCodeTextField) {
        self.verificationString = string;
    }
    if (self.phoneString.length && self.verificationString.length > 0) {
        [self.boundBtn setBackgroundColor:getColor(mainRedColor)];
        [self.boundBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.boundBtn.userInteractionEnabled = YES;
    }else{
        [self.boundBtn setBackgroundColor:getColor(mainColor)];
        [self.boundBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        self.boundBtn.userInteractionEnabled = NO;
    }
    return YES;
}

//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11){
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}
- (void)showView{
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
    }];
}
- (void)cancelView{
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 0 ;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
#pragma mark - networking
/**
 *  显示错误信息
 *
 *  @param error 返回的错误信息
 */
- (void) showError:(NSError*)error{
    switch (error.code) {
        case NSURLErrorNotConnectedToInternet:
            [self makeToast:@"请检查你的网络" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorTimedOut:
            [self makeToast:@"请求超时，请查看你的网络" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorCannotConnectToHost:
            [self makeToast:@"服务器繁忙，请稍后重试" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorNetworkConnectionLost:
            [self makeToast:@"处理过程中网络中断，请重试" duration:1 position:CSToastPositionCenter];
            break;
        default:
            [self makeToast:@"未知错误" duration:1 position:CSToastPositionCenter];
            break;
    }
}
@end
